﻿using AutoMapper;
using MediatR;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.Permission;

namespace RBAC.Write.Api.Application.Handler.Permission
{
    public class CreatePermissionHandler : IRequestHandler<CreatePermissionCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreatePermissionHandler> logger;

        public CreatePermissionHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<CreatePermissionHandler> logger)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreatePermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var permission =mapper.Map<PermissionModel>(request);
            var r = permissionRepository.Create(permission);
            if(r>0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "添加成功";
                logger.LogInformation("添加权限成功");
                return Task.FromResult(res);
                
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "添加失败";
                res.Data = r;
                logger.LogError("添加权限失败");
                return Task.FromResult(res);
            }
        }
    }
}
